package com.gxa.interceptor;

import com.github.pagehelper.util.StringUtil;
import com.gxa.exception.SystemException;
import com.gxa.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author htt
 * @create 2021-03-20
 * project overview
 */
public class JWtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Authorization");
        if (StringUtil.isEmpty(token)){
            //token为空
            throw new SystemException(6001, "token不能为空!");
        }
        //token不为空 token验证
        Integer userId = JwtUtil.getUserId(token);
        //验证token
        if (!JwtUtil.verfy(token, userId)) {
            //token错误
            throw new SystemException(6002, "token错误，请重新登录！");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
